<script setup lang="ts">
import { onMounted, ref } from 'vue';
import Taro, { useRouter } from '@tarojs/taro';
import type { CalendarCardDay, FormInstance } from '@nutui/nutui-taro';
import { useDateFormat } from '@vueuse/core';
import type { Receiving } from '@/interface';
import { createReceiving, delReceiving, updateReceiving } from '@/service/api';
import { showErrorMsg } from '@/service/request/helpers';

const receivingForm = ref<Receiving>({
  id: '',
  bookId: '',
  guestName: '',
  amount: '',
  receiveDate: '',
  remark: '',
  reciprocated: false
});

const formRef = ref<FormInstance>();

// 默认为新增页面，有可能是编辑页面，需要显示删除和保存按钮
const settingPage = ref<boolean>(false);

const calendarCardShow = ref(false);
const onDayClick = (day: CalendarCardDay) => {
  receivingForm.value.receiveDate = `${day.year}-${day.month}-${day.date}`;
  calendarCardShow.value = false;
};
const selectedDate = ref<Date>(new Date());
const onDateFocus = () => {
  if (!receivingForm.value.receiveDate) return;
  selectedDate.value = new Date(receivingForm.value.receiveDate);
};
onMounted(() => {
  const router = useRouter();
  const { tag } = router.params;
  if (tag) {
    settingPage.value = true;
    const pages = Taro.getCurrentPages();
    const current = pages[pages.length - 1];
    current.getOpenerEventChannel().on('initData', (data: Receiving) => {
      receivingForm.value.id = data.id;
      receivingForm.value.bookId = data.bookId;
      receivingForm.value.guestName = data.guestName;
      receivingForm.value.amount = data.amount;
      receivingForm.value.receiveDate = useDateFormat(data.receiveDate, 'YYYY-MM-DD').value;
      receivingForm.value.remark = data.remark;
      selectedDate.value = new Date(data.receiveDate!);
    });
  } else {
    const { bookId, receiveDate } = router.params;
    receivingForm.value.bookId = bookId!;
    receivingForm.value.receiveDate = useDateFormat(receiveDate, 'YYYY-MM-DD').value;
    selectedDate.value = new Date(receiveDate!);
  }
});

const resetForm = () => {
  receivingForm.value.id = '';
  receivingForm.value.guestName = '';
  receivingForm.value.amount = '';
  receivingForm.value.remark = '';
  formRef.value?.reset();
};

const flushReceivingList = () => {
  const pages = Taro.getCurrentPages();
  const current = pages[pages.length - 1];
  current.getOpenerEventChannel().emit('flushData');
};

const onSave = (back: boolean) => {
  formRef.value?.validate().then(res => {
    const { valid, errors } = res as { valid: boolean; errors: Array<object> };
    if (valid) {
      Taro.showLoading({ title: '保存中...' });
      if (receivingForm.value.id) {
        updateReceiving(receivingForm.value)
          .then(() => {
            Taro.hideLoading();
            if (back) {
              Taro.navigateBack({
                delta: 1
              });
              flushReceivingList();
            } else {
              resetForm();
            }
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      } else {
        createReceiving(receivingForm.value)
          .then(() => {
            Taro.hideLoading();
            if (back) {
              Taro.navigateBack({
                delta: 1
              });
              flushReceivingList();
            } else {
              resetForm();
            }
          })
          .catch((err: Service.RequestError) => {
            Taro.hideLoading();
            showErrorMsg(err.message);
          });
      }
    } else {
      console.log(errors[0]);
      showErrorMsg(`${errors[0]}`);
    }
  });
};

const onSaveAndBack = () => {
  onSave(true);
};

const onSaveAndContinue = () => {
  onSave(false);
};

const showDeleteDialog = ref<boolean>(false);
const onDelete = () => {
  showDeleteDialog.value = true;
};
const onDelConfirm = () => {
  if (receivingForm.value.id) {
    Taro.showLoading({ title: '删除中...' });
    delReceiving(receivingForm.value.id)
      .then(() => {
        Taro.hideLoading();
        Taro.navigateBack({
          delta: 1
        });
        flushReceivingList();
      })
      .catch((err: any) => {
        Taro.hideLoading();
        showErrorMsg(err.message);
      });
  }
};

const onCancel = () => {
  showDeleteDialog.value = false;
};
</script>

<template>
  <basic-layout :show-tab-bar="false">
    <custom-nav-bar left-show title="添加收礼记录" />
    <div class="w-375px text-30px">
      <nut-form ref="formRef" star-position="right" :model-value="receivingForm" label-position="top">
        <nut-form-item
          label="宾客姓名"
          prop="guestName"
          required
          :rules="[{ required: true, message: '请填写宾客姓名' }]"
        >
          <nut-input v-model="receivingForm.guestName" placeholder="" type="text" :border="false" />
        </nut-form-item>
        <nut-form-item label="礼金金额" prop="amount" required :rules="[{ required: true, message: '请填写礼金金额' }]">
          <nut-input v-model="receivingForm.amount" placeholder="" type="text" :border="false" />
        </nut-form-item>
        <nut-form-item
          label="收礼日期（默认为礼簿收礼日期）"
          prop="receiveDate"
          required
          :rules="[{ required: true, message: '请选择收礼日期' }]"
        >
          <nut-input
            v-model="receivingForm.receiveDate"
            placeholder=""
            type="text"
            readonly
            :border="false"
            @click="calendarCardShow = true"
            @focus="onDateFocus"
          />
          <nut-popup
            :visible="calendarCardShow"
            position="bottom"
            safe-area-inset-bottom
            @click-overlay="calendarCardShow = false"
          >
            <nut-calendar-card v-model="selectedDate" type="single" @day-click="onDayClick"></nut-calendar-card>
          </nut-popup>
        </nut-form-item>
        <nut-form-item label="备注信息">
          <textarea
            v-model="receivingForm.remark"
            placeholder=" "
            class="bg-#f7f8fa h-100px w-100% b-rd-5px right-4px left-1px"
          />
        </nut-form-item>
      </nut-form>
      <nut-space direction="vertical" fill>
        <nut-button class="hoo-btn hoo-btn--confirm" block plain @click="onSaveAndBack">
          {{ settingPage ? '保存' : '保存并返回' }}
        </nut-button>
        <nut-button v-show="!settingPage" class="hoo-btn hoo-btn--confirm" block plain @click="onSaveAndContinue">
          保存后继续添加
        </nut-button>
        <nut-button v-show="settingPage" class="hoo-btn hoo-btn--delete" block plain @click="onDelete">删除</nut-button>
      </nut-space>
      <nut-dialog
        v-model:visible="showDeleteDialog"
        title="警告"
        content="数据删除后不能回复，确认是否删除?"
        @cancel="onCancel"
        @ok="onDelConfirm"
      />
    </div>
  </basic-layout>
</template>

<style lang="scss">
@import '@/styles/custom';
</style>
